﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Auth.Commands;

public class RegisterCommandValidator : AbstractValidator<RegisterCommand>
{
    private readonly IApplicationDbContext _context;
    public RegisterCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(v => v.UserName)
             .MustAsync(BeUniqueUserName).WithMessage($"用户名已存在！"); ;
    }

    /// <summary>
    /// 校验用户名是否唯一
    /// </summary>
    /// <param name="userName">用户名称</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns></returns>
    private async Task<bool> BeUniqueUserName(string userName, CancellationToken cancellationToken)
    {
        return !(await _context.Users.AnyAsync(x => x.UserName == userName, cancellationToken));
    }
}
